﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace DO.Workflows
{
    public class DependencyConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
                return true;
            return false;
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(List<Guid>))
                return true;
            return false;
        }

        /// <summary>
        /// string -> List of Guid 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="culture"></param>
        /// <param name="value"></param>
        /// <param name="destinationType"></param>
        /// <returns></returns>
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            List<Guid> dependencies = new List<Guid>();
            if (value != null && value.ToString().Length > 0)
            {
                string[] depencendencyIDs = value.ToString().Split(new char[] { ',' });
                foreach (string depID in depencendencyIDs)
                {
                    Guid guid = new Guid(depID);
                    dependencies.Add(guid);
                }
            }
            return dependencies;
        }

        /// <summary>
        /// List of Guids to string
        /// </summary>
        /// <param name="context"></param>
        /// <param name="culture"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            StringBuilder buffer = new StringBuilder();
            if (value != null && value.GetType() == typeof(List<Guid>))
            {
                List<Guid> ids = (List<Guid>)value;
                foreach (Guid id in ids)
                {
                    if (buffer.Length > 0)
                        buffer.Append(",");
                    buffer.Append(id.ToString());
                }
            }
            return buffer.ToString();
        }
    }
}
